#include <nice2d/application.h>
#include <nice2d/deserializerfactory.h>
#include <nice2d/widgets/desktop.h>
#include <nice2d/widgets/radiobox.h>

IMPLEMENT_OBJECT(RadioBoxStyle, ControlStyle)

RadioBoxStyle::RadioBoxStyle()
{
    selectedStyle = std::make_shared<ControlStyle>();
}

PTree RadioBoxStyle::serialize()
{
    PTree node;
    SERIALIZE_BASE_OBJECT(node, ControlStyle);
    node.add_child("selectedStyle", selectedStyle->serializeThisClass());
    return node;
}

void RadioBoxStyle::deserialize(const PTree &node)
{
    DESERIALIZE_BASE_OBJECT(node, ControlStyle)
    selectedStyle = DeserializerFactory::deserialize<ControlStyle>("selectedStyle", node);
}

void RadioBoxStyle::sync()
{
}

IMPLEMENT_OBJECT(RadioBox, Control)

class RadioBoxData
{
public:
    RadioBox *radioBox = nullptr;
    bool selected = false;
    std::shared_ptr<ControlRadioSelector> selector;
    bool addedToSelector = false;
};

RadioBox::RadioBox(std::shared_ptr<ControlRadioSelector> selector):
    data(new RadioBoxData)
{
    data->radioBox = this;
    auto desktop = GET_APPLICATION_COMPONENT(Desktop);
    setControlStyle(desktop->getControlStyle("RadioBox"));
}

RadioBox::~RadioBox()
{
}

bool RadioBox::isSelected()
{
    return data->selected;
}

void RadioBox::selected()
{
    data->selected = true;
}

void RadioBox::unselected(ControlPointer control)
{
    (void)control;
    data->selected = false;
}

void RadioBox::selected(ControlPointer control)
{
    (void)control;
    data->selected = true;
}

void RadioBox::onMouseEnter()
{
    onStyleChanged();
}

void RadioBox::onMouseExit()
{
    onStyleChanged();
}

void RadioBox::onMousePressed(sf::Mouse::Button button)
{
    if (sf::Mouse::Left == button) {
        if (data->selector)
            data->selector->select(as<Control>());
    }
}

void RadioBox::onUpdateControl(float deltaTime)
{
    if (!data->addedToSelector) {
        data->addedToSelector = true;
        data->selector->addControl(as<Control>());
    }
}

void RadioBox::onStyleChanged()
{
    Control::onStyleChanged();
    auto style = getTemplateStyle<RadioBoxStyle>();
    if (isSelected()) {
        if (isUnderMouse())
            setBackground(style->selectedStyle->hoverBackground);
        else
            setBackground(style->selectedStyle->normalBackground);
    }
}

DECL_DESERIALIZER_FACTORY_IMPL(RadioBoxStyle)
